<template>
  <div>
    <div class="container">
      <div class="userInfo">
        <img :src="userInfo.avatarUrl" alt="">
        <button class="btn" v-if="!userInfo.openId" open-type="getUserInfo" @getuserinfo="wxLogin">{{userInfo.nickName}}</button>
        <p v-if="userInfo.openId" >{{userInfo.nickName}}</p>
      </div>
      <YearProgress></YearProgress>
      <button v-if="userInfo.openId" @click="scanBook" class="btn">添加图书</button>
    </div>
  </div>
</template>
<script>
import qcloud from 'wafer2-client-sdk'
import config from '../../config'
import { showSuccess, post, showModal } from '../../utils'
import YearProgress from '@/components/YearProgress'
export default {
  components: {
    YearProgress
  },
  data () {
    return {
      userInfo: {
        avatarUrl: '../../../static/img/unlogin.png',
        nickName: '点击登录'
      }
    }
  },
  methods: {
    async addBook (isbn) {
      const res = await post('/weapp/addbook', {
        isbn: isbn,
        openId: this.userInfo.openId
      })
      if (res.code === 0 && res.data.title) {
        showModal('添加成功', `${res.data.title}添加成功`)
      }
    },
    wxLogin () {
      console.log('xxx')
      qcloud.setLoginUrl(config.loginUrl)
      const self = this
      qcloud.login({
        success: function (userInfo) {
          console.log('success', userInfo)
          showSuccess('success')
          wx.setStorageSync('userInfo', userInfo)
          self.userInfo = userInfo
        },
        fail: (error) => {
          console.log(error)
        }
      })
    },
    scanBook () {
      wx.scanCode({
        success: (res) => {
          if (res.result) {
            console.log(res.result)
            this.addBook(9787115326560)
          }
        }
      })
    }
  },
  onShow () {
    let user = wx.getStorageSync('userInfo')
    if (user) {
      this.userInfo = user
    }
  }
}
</script>
<style lang="scss">
 .container{
  padding: 0 30rpx;
  text-align: center;
  .userInfo{
    margin-top: 100rpx;
    img{
      width: 150rpx;
      height: 150rpx;
      margin: 20rpx;
      border-radius: 50%;
    }
  }
}
</style>


